<?php
namespace app\admin\controller;
use app\model\Product as ProductModel;
use think\Db;

use app\lib\aliyun\Api as aliyunApi;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;


class Product extends Base
{
    public function __construct(){
        $model = new ProductModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '产品';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $this->page_info['view'] = 'save';
        $model = $this->model;

        $categorys = [];
        $p_categorys = Db::name('category')->where('pid',0)->select();
        foreach ($p_categorys as $k => $vo) {
            $categorys[] = $vo;
            $childs = Db::name('category')->where('pid',$vo['id'])->select();
            foreach ($childs as $child) {
                $child['name'] = ' ->'.$child['name'];
                $categorys[] = $child;
            }
        }
        $categorys = arrayParamExtract($categorys,'id','name');

        $collects = Db::name('collect')->field('uuid,name')->order('id asc')->select();
        $collects = arrayParamExtract($collects,'uuid','name');

        $fields = [
            'collect'=>['name'=>'来源','type'=>'select1','params'=>$collects],
            'category_id'=>['name'=>'分类','type'=>'select1','params'=>$categorys],
            'name'=>['name'=>'名称','type'=>'text'],
            'cover'=>['name'=>'图片','type'=>'file'],
            'description'=>['name'=>'描述','type'=>'textarea'],
            'tags'=>['name'=>'标签（多个用,分割）','type'=>'text'],
            'group'=>['name'=>'分组','type'=>'text'],
            
        ];
        $valids = createPageValid($fields);

        $content_types = [
            'text'=>'文本',
            'grid'=>'表格',
            'li'=>'列表',
        ];

        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids,
            'content_types'=>$content_types
        ]);
    }

    public function assignSearchs(){
        $model = $this->model;

        $categorys = [];
        $p_categorys = Db::name('category')->where('pid',0)->select();
        foreach ($p_categorys as $k => $vo) {
            $categorys[] = $vo;
            $childs = Db::name('category')->where('pid',$vo['id'])->select();
            foreach ($childs as $child) {
                $child['name'] = ' ->'.$child['name'];
                $categorys[] = $child;
            }
        }
        $categorys = arrayParamExtract($categorys,'id','name');

        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
                ['key'=>'group','name'=>'分组','type'=>'text'],
                ['key'=>'category_id','name'=>'分类','type'=>'select1_1','params'=>$categorys] 
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'group','type'=>'='],
            ['key'=>'category_id','type'=>'=']
        ];
        $map = getSearchParam($map_params);

        // 显示筛选
        $this->assignSearchs();

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        $list = $model->where($map)->order('id','asc')->paginate($page_param);
        $page = $list->render();

        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['category_name'] = Db::name('category')->where('id',$vo['category_id'])->value('name');
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function export(){
        set_time_limit ( 0 );
        ini_set('memory_limit','40960M');

        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'code','type'=>'like'],
            ['key'=>'category_id','type'=>'=']
        ];
        $map = getSearchParam($map_params);

        $model = $this->model;
        $list = $model->where($map)->order('id','asc')->select();   

        $categorys = Db::name('category')->field('id,name')->select();
        $categorys = arrayParamExtract($categorys,'id','name');
        
        $data = [];
        $title = ['ID','分类','名称','代码','折扣','类型'];
        foreach ($list as $k => $vo) {
            $tmp = [
                $vo['id'],
                $categorys[$vo['category_id']],
                $vo['name'],
                $vo['code'],
                $vo['discount'],
                $vo['type']
            ];
            $data[] = $tmp;
        }
        exportCsv(date('YmdHis'),$title,$data);
    }


    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['collect','category_id','name'],
                'nomust'=>['description','tags','group','cover','content']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }

            if (!empty($save_data['content'])) {
                $content = [];
                for ($i=0; $i < count($save_data['content']['title']); $i++) { 
                    $content[] = [
                        'title'=>$save_data['content']['title'][$i],
                        'type'=>$save_data['content']['type'][$i],
                        'content'=>$save_data['content']['content'][$i],
                    ];
                }

                $save_data['content'] = json_encode($content,JSON_UNESCAPED_UNICODE);
            }
           
        }
        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        if (request()->isPost()) {
            $fields = [
                'must'=>['collect','category_id','name'],
                'nomust'=>['description','tags','group','cover','content']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            
            if (!empty($save_data['content'])) {
                $content = [];
                for ($i=0; $i < count($save_data['content']['title']); $i++) { 
                    $content[] = [
                        'title'=>$save_data['content']['title'][$i],
                        'type'=>$save_data['content']['type'][$i],
                        'content'=>$save_data['content']['content'][$i],
                    ];
                }

                $save_data['content'] = json_encode($content,JSON_UNESCAPED_UNICODE);
            }
        }
        return parent::updateData($id,$save_data);
    }


    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function vco(){
        $login_url = 'https://vco.console.aliyun.com';
        $login_res = $this->Login($login_url);
        return redirect($login_res);
    }

    // public function import(){
    //     $file_path = 'C:/tmp.xlsx';
    //     $extension = strtolower(pathinfo($file_path,PATHINFO_EXTENSION));
    //     if ($extension =='xlsx') {
    //         $objReader = new \PHPExcel_Reader_Excel2007();
    //         $objExcel = $objReader->load($file_path);
    //     } else if ($extension =='xls') {
    //         $objReader = new \PHPExcel_Reader_Excel5();
    //         $objExcel = $objReader->load($file_path);
    //     }

    //     $list=$objExcel->getsheet(0)->toArray();   //转换为数组格式
    //     array_shift($list);  //删除第一个数组(标题);

    //     // foreach ($list as $k => $vo) {
    //     //     $code = trim($vo[1]);
    //     //     if ( Db::name('product')->where('code',$code)->count() > 0 ) {
    //     //         Db::name('product')->where('code',$code)->update([
    //     //             'name'=>trim($vo[0]),
    //     //             'discount'=>trim($vo[6])
    //     //         ]);
    //     //     }else{
    //     //         Db::name('product')->where('code',$code)->insert([
    //     //             'name'=>trim($vo[0]),
    //     //             'code'=>$code,
    //     //             'discount'=>trim($vo[6]),
    //     //             'ctime'=>time()
    //     //         ]);
    //     //     }
    //     // }

    //     dump($list);die;


    //     $file_path = 'C:/tmp.csv';
    //     $handle = fopen( $file_path, "rb" );
    //     $data = [];
    //     while (!feof($handle)) {
    //         $data[] = fgetcsv($handle);
    //     }
    //     fclose($handle);
    //     dump($data);die;

    //     // $data = eval('return ' . iconv('gb2312', 'utf-8', var_export($data, true)) . ';');//字符转码操作

    //     return $data;
    // }

    // 获取登录令牌
    public function GetSigninToken(){
        $uinfo = Db::name('user')->field('id,pk')->where('id',1)->find();
        $api_controller = new aliyunApi();
        $credentials = $api_controller->AssumeRole($uinfo['pk']);
        if ($credentials['status'] == 0) {
            return $credentials;
        }
        $credentials = $credentials['data'];

        // SK初始化账号Client
        $api_controller->accessKeyClient($credentials['AccessKeyId'], $credentials['AccessKeySecret']);
        $options = [
            'TicketType' => 'mini',
            'AccessKeyId'=>$credentials['AccessKeyId'],
            'AccessKeySecret'=>$credentials['AccessKeySecret'],
            'SecurityToken'=>$credentials['SecurityToken']
        ];
        try {
            $result = AlibabaCloud::rpc()
                      // ->product('federation')
                      ->version('2015-04-01')
                      ->action('GetSigninToken')
                      ->method('POST')
                      ->host('signin.aliyun.com/federation')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            if (!empty($result['SigninToken'])) {
                $result = ['status'=>1,'data'=>$result['SigninToken']];
            }else{
                $result = ['status'=>0,'msg'=>$result['Message']];
            }
        } catch (ClientException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        }
        return $result;
    }

    public function Login($login_url){
        $token = $this->GetSigninToken();
        if ($token['status'] == 0) {
            return $token;
        }

        $options = [
            'Action'=>'Login',
            'LoginUrl' => 'https://delirhy.ccjcch.com/api/plan/callback',
            'Destination'=>$login_url,
            'SigninToken'=>$token['data']
        ];
        return 'https://signin.aliyun.com/federation'.'?'.http_build_query($options);
    }

    public function import(){
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('C:/333.xlsx');
        $excels=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excels);  //删除第一个数组(标题);

        $save_datas = [];
        $category = '';
        $category_id = 0;
        foreach ($excels as $k => $vo) {
            if (!empty($vo[1])) {
                $category = $vo[1];
                if (Db::name('category')->where('name',$category)->count() == 0) {
                    Db::name('category')->insert([
                        'name'=>$category
                    ]);
                }
                $category_id = Db::name('category')->where('name',$category)->value('id');
            }
            
            $data = [
                'name'=>$vo[4],
                'code'=>$vo[3],
                'category_id'=>$category_id,
                'console_url'=>null,
                'buy_url'=>null
            ];
            if (empty($data['code'])) {
                continue;
            }


            if ( !empty($save_datas[$data['code']]) ) {
                if (strpos($vo[5],'列表') !== false && empty($save_datas[$data['code']]['console_url'])) {
                    $save_datas[$data['code']]['console_url'] = $vo[6];
                }elseif(strpos($vo[5],'创建') !== false && empty($save_datas[$data['code']]['buy_url'])){
                    $save_datas[$data['code']]['buy_url'] = $vo[6];
                }
            }else{
                if (strpos($vo[5],'列表') !== false) {
                    $data['console_url'] = $vo[6];
                }elseif(strpos($vo[5],'创建') !== false){
                    $data['buy_url'] = $vo[6];
                }

                $save_datas[$data['code']] = $data;
            }
        }

        Db::name('product')->insertAll($save_datas);
        dump($excels);die;
    }

    public function import2(){
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('C:/444.xlsx');
        $excels=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excels);  //删除第一个数组(标题);

        $save_datas = [];
        foreach ($excels as $k => $vo) {
            if (Db::name('product')->where('code',$vo[0])->count() > 0) {
                continue;
            }
            
            $data = [
                'name'=>$vo[1],
                'code'=>$vo[0],
                'category_id'=>0
            ];
            if (empty($data['code'])) {
                continue;
            }


            if ( empty($save_datas[$data['code']]) ) {
                $save_datas[$data['code']] = $data;
                
            }
        }

        Db::name('product')->insertAll($save_datas);
        dump($excels);die;
    }

   
}
